package com.hrm.controller;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.hrm.pojo.Users;
import com.hrm.pojo.dto.UserList;
import com.hrm.pojo.dto.ValidateCodeRequest;
import com.hrm.service.UsersService;
import com.hrm.utils.DuanxinUtils;
import com.hrm.utils.JwtUtil;
import com.hrm.utils.entity.PageResult;
import com.hrm.utils.entity.Result;
import com.hrm.utils.entity.StatusCode;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.aliyun.teautil.Common.toJSONString;

@RestController
@RequestMapping("/users")
@Api(tags = "用户模块的接口")
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private DuanxinUtils duanxinUtils;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation(value = "用户注册也用于用户增加")
    @PostMapping("/reg")
    public Result regUser(@RequestBody Users users) throws Exception {
        boolean flag = usersService.register(users);
        return new Result(flag, flag == true ? StatusCode.SUCCESS : StatusCode.ERROR, flag == true ? "注册成功" : "注册失败");
    }

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody Users users) throws Exception {
        Users LoginUser = usersService.login(users.getLoginname(), users.getPassword());
        if (LoginUser == null) {
            throw new Exception("登录失败");
        }
        //使用用户信息生成token
        String token = jwtUtil.createJWT(LoginUser.getId() + "", LoginUser.getLoginname(), LoginUser.getStatus() + "");
        //把token存储到redis中，key为username，value为token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token, token, 1, TimeUnit.HOURS); //设置过期时间为一小时
        System.out.println(token);
        //将token返回前端
        return new Result(LoginUser != null, StatusCode.SUCCESS, "登录成功", new String[]{token, LoginUser.getId() + "", LoginUser.getUsername(), LoginUser.getStatus() + ""});
    }

    @ApiOperation(value = "用户修改密码")
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestParam String oldPassword, @RequestParam String newPassword, HttpServletRequest request) throws Exception {
        //获取token中的用户信息
        Claims claims = jwtUtil.parseJWT(request.getHeader("Authorization"));
        Integer id = Integer.parseInt(claims.getId());
        boolean b = usersService.updatePwd(id, oldPassword, newPassword);
        if (!b) {
            throw new Exception("密码修改失败");
        }
        return new Result(b, StatusCode.SUCCESS, "密码修改成功");
    }

    @ApiOperation(value = "用户模糊查询用户信息列表前端分页展示")
    @PostMapping("/list")
    public Result<PageResult<Users>> list(@RequestBody UserList userList) throws Exception {
        Users users = new Users();
        users.setUsername(userList.getUsername());
        users.setStatus(userList.getStatus());
        PageResult<Users> userss = usersService.findByUsernameAndStatus(userList.getPageNum(), userList.getPageSize(), users);
        if (userss.getTotal() == 0) {
            throw new Exception("用户数据为空，请添加需要的用户数据");
        }
        return new Result(true, StatusCode.SUCCESS, "查询成功", userss);
    }


    @ApiOperation(value = "用户删除一个或者多个用户信息")
    @DeleteMapping("/delete")
    public Result deleteInfo(@RequestBody  Integer[] ids) throws Exception {
        boolean b = usersService.deleteUsers(ids);
        if (!b) {
            throw new Exception("删除失败");
        }
        return new Result(b, StatusCode.SUCCESS, "删除成功");
    }

    @ApiOperation(value = "用户点击修改信息时候获取用户信息显示")
    @PostMapping("/usersInfo/{id}")
    public Result usersInfo(@PathVariable Integer id) throws Exception {
        //根据id查询用户信息
        Users result = usersService.findById(id);
        if (result == null) {
            throw new Exception("用户信息不存在");
        }
        return new Result(true, StatusCode.SUCCESS, "查询成功", result);
    }

    @ApiOperation(value = "用户修改用户信息")
    @PutMapping("/update")
    public Result updateInfo(@RequestBody Users users) throws Exception {
        boolean b = usersService.updateUser(users);
        if (!b) {
            throw new Exception("用户信息修改失败");
        }
        return new Result(b, StatusCode.SUCCESS, "用户信息修改成功");
    }

    @ApiOperation(value = "用户退出登录清除token的API")
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //清除token
        String token = request.getHeader("Authorization");
        if (token != null && !token.isEmpty()) {
            // 清除JWT
            jwtUtil.clearJWT(token);

            // 清除Redis中的token
            if (stringRedisTemplate.hasKey(token)) {
                stringRedisTemplate.delete(token);
            }
        }
        response.setHeader("Authorization", "");
        return new Result(true, StatusCode.SUCCESS, "退出登录成功");
    }

    @ApiOperation(value = "用户忘记密码，通过手机号获取验证码")
    @PostMapping("/sendCode")
    public Result sendCode(String phone) throws Exception {
        try {
            //判断手机号是否存在
            Users users = usersService.findByPhone(phone);
            if (users == null) {
                throw new Exception("手机号未注册");
            }
            SendSmsResponse sendSmsResponse = duanxinUtils.sendSms(phone);
            System.out.println(toJSONString(sendSmsResponse));
            // 检查短信发送的响应结果
            if ("OK".equals(sendSmsResponse.getBody().getCode())) {
                // 短信发送成功，获取生成的验证码
                // 此处需要通过 Redis 获取存储的验证码
                String code = stringRedisTemplate.opsForValue().get(phone); // 获取存储在 Redis 中的验证码
                System.out.println("验证码：" + code);
                return new Result(true, StatusCode.SUCCESS, "验证码发送成功", code);
            } else {
                return new Result(false, StatusCode.ERROR, "触发小时级流控Permits",toJSONString(sendSmsResponse));
            }
        } catch (Exception e) {
            // 记录异常信息
            System.err.println("发送验证码时出错：" + e.getMessage());
            return new Result(false, StatusCode.ERROR, "发送验证码失败，请重试");
        }
    }
    @ApiOperation(value = "验证验证码")
    @PostMapping("/validateCode")
    public Result validateCode(@RequestBody ValidateCodeRequest request) throws Exception {
        try {
            // 从 Redis 获取验证码
            String storedCode = stringRedisTemplate.opsForValue().get(request.getPhone());

            // 验证验证码
            if (storedCode == null) {
                return new Result(false, StatusCode.ERROR, "验证码已失效，请重新请求验证码");
            }
            if (!storedCode.equals(request.getCode())) {
                return new Result(false, StatusCode.ERROR, "验证码错误");
            }

            return new Result(true, StatusCode.SUCCESS, "验证码验证成功");
        } catch (Exception e) {
            // 记录异常信息
            System.err.println("验证验证码时出错：" + e.getMessage());
            return new Result(false, StatusCode.ERROR, "验证码验证失败，请重试");
        }
    }

    @ApiOperation(value = "用户忘记密码，通过手机号获取验证码重置密码")
    @PutMapping("/resetPassword")
    public Result resetPassword(String phone, String newPassword) throws Exception {
        boolean b = usersService.updatePwdByPhone(phone, newPassword);
        return new Result(b, StatusCode.SUCCESS, "密码重置成功");
    }

}
